// @flow
import React, { Component } from 'react'
import styles from './Fault.css'
import { Input, Button, Form } from 'antd'
import FaultGrid1 from './FaultGrid1'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const FormItem = Form.Item
import { connect } from 'react-redux'
import moment from 'moment'
import EventFilter from 'components/EventFilter'

type Props = {
  history: Object,
  form: Object,
  userId: string
}
type States = {
  deviceData: Array<any>,
  rowData: Array<Object>,
  total: number,
  current: number,
  pageSize: number
}
class Fault1 extends Component {
  props: Props
  state: States
  queryUrl: String
  getFaults: Function
  addFault: Function
  handleSearch: Function
  getDeviceData: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      deviceData: [],
      rowData: [],
      total: 0,
      current: 1,
      pageSize: 20
    }
    this.handleSearch = this.handleSearch.bind(this)
    this.getFaults = this.getFaults.bind(this)
    this.addFault = this.addFault.bind(this)
    this.getDeviceData = this.getDeviceData.bind(this)
  }
  handleSearch (searchQuery) {
    this.queryUrl = searchQuery
    this.getFaults(1, 20)
  }
  // handleSearch (e: any) {
  //   e.preventDefault()
  //   this.props.form.validateFields((err, values) => {
  //     if (!err) {
  //       console.log(values)
  //     }
  //   })
  // }
  componentWillMount () {
    this.getDeviceData()
  }
  getDeviceData () {
    universalFetch(`${__SERVICE_API__}device/devices?pageSize=20000`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        deviceData: json.result
      }, () => {
        this.getFaults(this.state.current, this.state.pageSize)
      })
    })
    .catch((error) => {
      console.error(error)
    })
  }

  getFaults (page: number, pageSize: number) {
    let queryUrl = this.queryUrl || ``
    const { userId } = this.props
    universalFetch(`${__SERVICE_API__}device/events1/events?userId=${userId}&pageNum=${page}&pageSize=${pageSize}&order=desc${queryUrl}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          current: page,
          total: json.pageInfo.total,
          rowData: json.result.map((d, i) => {
            d['startTime'] = moment(d.startTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
            d['endTime'] = moment(d.endTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
            return d
          })
          // rowData: json.result.map((d, i) => {
          //   const deviceD = deviceData.filter((dd) => dd.id === d.deviceId)
          //   if (deviceD.length > 0) {
          //     d['deviceName'] = deviceD[0].name || ''
          //     d['deviceNo'] = deviceD[0].deviceNo || ''
          //   }
          //   return d
          // })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  addFault () {
    this.props.history.push('/business/fault-add1')
  }
  render () {
    const { rowData, current, pageSize, total } = this.state
    // const { getFieldDecorator } = this.props.form
    return (
      <div className={styles['main']}>
        <div className={styles['action']}>
          {/* <Button type='primary' onClick={this.addFault} style={{ marginTop: '6px' }}>添加故障记录</Button> */}
          <div style={{ paddingBottom: 5, paddingLeft: 12 }}>
            <EventFilter getData={this.handleSearch} />
          </div>
          {/* <Form layout='inline' className={styles['tool-bar']}>
            <FormItem>
              {getFieldDecorator('name')(
                <Input placeholder='事件名称' />
              )}
            </FormItem>
            <FormItem>
              {getFieldDecorator('type')(
                <Input placeholder='事件类型' />
              )}
            </FormItem>
            <FormItem>
              {getFieldDecorator('prople')(
                <Input placeholder='负责人' />
              )}
            </FormItem>
            <Button icon='search' onClick={this.handleSearch} style={{ marginTop: '2px' }} />
          </Form> */}
        </div>
        <FaultGrid1 {...{
          current,
          pageSize,
          total,
          refreshFaults: this.getFaults,
          rowData: rowData,
          history: this.props.history
        }} />
      </div>
    )
  }
}

const mapStateToProps = state => {
  return {
    userId: state.user.userId,
    userMenu: state.menu.userMenu
  }
}
export default connect(mapStateToProps, {})(Form.create()(Fault1))
